package org.ssssssss.magicapi.redis;

import com.yonyou.iuap.yms.cache.adapter.YMSCacheFactory;
import com.yonyou.iuap.yms.cache.factory.YMSRedisConnectionFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.ssssssss.magicapi.core.config.MagicAPIProperties;
import org.ssssssss.magicapi.core.config.MagicPluginConfiguration;
import org.ssssssss.magicapi.core.config.Resource;
import org.ssssssss.magicapi.core.model.Plugin;

@Configuration
public class MagicRedisConfiguration implements MagicPluginConfiguration {

    private final MagicAPIProperties properties;

    public MagicRedisConfiguration(MagicAPIProperties properties) {
        this.properties = properties;
    }


    /**
     * 使用Redis存储
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "magic-api", name = "resource.type", havingValue = "redis")
    public org.ssssssss.magicapi.core.resource.Resource magicRedisResource(YMSCacheFactory ymsCacheFactory) {
        Resource resource = properties.getResource();
        StringRedisTemplate tp = ymsCacheFactory.createStringRedisTemplate("c-yondif-cpd-ocm_redis");
        return new RedisResource(tp, resource.getPrefix(), resource.isReadonly());
    }

    /**
     * 注入redis模块
     */
    @Bean
    public RedisModule redisFunctions(YMSCacheFactory ymsCacheFactory) {
        return new RedisModule(ymsCacheFactory);
    }

    @Override
    public Plugin plugin() {
        return new Plugin("Redis");
    }
}
